package com.yint;

import com.yint.tree.Leaf;
import com.yint.tree.STATUS;
import com.yint.tree.Sequence;
import com.yint.tree.Tree;
import com.yint.tree.UntilFailed;

/**
 * 行为树基本组件使用方法演示
 * 
 * 十分简单的模拟了一个npc一天中工作吃饭和睡觉
 * 
 * @author 殷田
 *
 */
public class Test
{
	public static void main( String[] argv )
	{
		Tree npc = new Tree();
		npc.addLong( "quit_time", System.currentTimeMillis() + 20 * 1000 );
		Sequence head = new Sequence();
		head.addSub( new UntilFailed( new Work() ) );
		head.addSub( new UntilFailed( new Eat() ) );
		head.addSub( new Sleep() );

		npc.setHead( head );
		System.out.println( "美好一天开始啦---------------" );
		while ( npc.entry() )
		{
			npc.tick();
			try
			{
				Thread.sleep( 1000 );
			}
			catch ( InterruptedException e )
			{
				e.printStackTrace();
			}
		}
		System.out.println( "美好一天结束啦---------------" );
	}

	public static class Work extends Leaf
	{

		@Override
		protected boolean onEntry( Tree tree )
		{
			if ( !tree.isExist( "quit_time" ) )
			{
				return false;
			}
			long interval = tree.getLong( "quit_time" ) - System.currentTimeMillis();
			if ( interval > 10 * 1000 )
			{
				return true;
			}
			return false;
		}

		@Override
		protected STATUS onTick( Tree tree )
		{
			System.out.println( "搬砖ing..." );
			return STATUS.SUCCEED;
		}

		@Override
		protected void onLeave( Tree tree, STATUS state )
		{

		}

	}

	public static class Eat extends Leaf
	{

		@Override
		protected boolean onEntry( Tree tree )
		{
			if ( !tree.isExist( "quit_time" ) )
			{
				return false;
			}
			long interval = tree.getLong( "quit_time" ) - System.currentTimeMillis();
			if ( interval > 5 * 1000 && interval <= 10 * 1000 )
			{
				return true;
			}
			return false;
		}

		@Override
		protected STATUS onTick( Tree tree )
		{
			System.out.println( "吃饭ing..." );
			return STATUS.SUCCEED;
		}

		@Override
		protected void onLeave( Tree tree, STATUS state )
		{

		}

	}

	public static class Sleep extends Leaf
	{

		@Override
		protected boolean onEntry( Tree tree )
		{
			if ( tree.isExist( "isSleeping" ) && tree.getBoolean( "isSleeping" ) )
			{
				return false;
			}
			if ( !tree.isExist( "quit_time" ) )
			{
				return false;
			}
			long interval = tree.getLong( "quit_time" ) - System.currentTimeMillis();
			if ( interval <= 5 * 1000 )
			{
				return true;
			}
			return false;
		}

		@Override
		protected STATUS onTick( Tree tree )
		{
			System.out.println( "开始睡觉喽" );
			tree.addBoolean( "isSleeping", true );
			return STATUS.SUCCEED;
		}

		@Override
		protected void onLeave( Tree tree, STATUS state )
		{
			// tree.removeParam( "isSleeping" );
		}

	}

}
